#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <signal.h>
#include <string.h>

using namespace std;

#define BUF_SZ 128
#define SOCKS_REQ_SZ 3
#define PORT 8088
#define ADDRESS "127.0.0.1"

int main(){
	int sock = socket(AF_INET, SOCK_DGRAM, 0);

	char y[4] = {127,0,0,1};
	printf("this address is: %s", inet_ntoa( *(struct in_addr *)&y));
	puts("");

	string addr(ADDRESS);
	sockaddr_in address;

	// BIND
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = inet_addr(addr.c_str());
	address.sin_port = htons(PORT);	
	if(bind(sock,(sockaddr*)&address,sizeof(address))==-1)
	{
	    close(sock);
	    perror("Neuspesny bind.");
	    return 1;	
	}

	sockaddr_in odKeho;
	socklen_t kolkoAdries;

	char buf[1000];
	int bytes;
	while((bytes = recvfrom(sock, buf, 1000, 0,(struct sockaddr *) &odKeho, &kolkoAdries)) != -1){
		if(bytes == 0)
			break;
		buf[bytes] = '\0';
 		printf("%s\n%s\n",inet_ntoa(odKeho.sin_addr), buf );
		buf[0] = 'A';
		if(sendto(sock, buf, bytes, 0, (struct sockaddr *)&odKeho, kolkoAdries) == -1)
			perror("sendto");
		if(sendto(sock, "a dalsia sprava pre poriadok", 28, 0, (struct sockaddr *)&odKeho, kolkoAdries) == -1)
			perror("sendto");
	}
	if(bytes != 0);
		perror("recvfrom");
	/*
	uint kolko = read(sock, buf, 1000);
	buf[kolko] = '\0';
	printf("SPRAVA: %s\n", buf);
		*/

	close(sock);

	return 0;
}
